import React from 'react'
import _ from 'underscore'
import $ from 'jquery'
import classnames from 'classnames'
import View from 'lib/View.jsx'
import {Scope} from 'lib/scopeFactory'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
import {saveAgentSettingApi} from '../apis/validApis/setting'
import agentSettingApi from '../apis/agentSetting'
import dispatcher from 'lib/dispatcher'
import DropdownList from 'lib/components/DropdownList.jsx'
import TagsInput from 'react-tagsinput'

class AgentSettingScope extends Scope {
  constructor(props){
    super(props)
    this.$state = {
      form:{
        saving:false,
        editable:false,
        errors:{}
      },
      list:[
        {label:'0.2',value:'0.2'},
        {label:'0.3',value:'0.3'},
        {label:'0.4',value:'0.4'},
        {label:'0.5',value:'0.5'},
        {label:'0.6',value:'0.6'}
      ]
    }
    this.agentApi = agentSettingApi()
  }
  $load(){
    this.agentApi.fetch().then((data) => {
      let tags = (data.agent.packageList || '').split(',');
      this.$state.packageName = data.app ? data.app.packageName : '';
      this.$state.form.values = data.agent
      this.$state.tags        = _.filter(tags, tag => $.trim(tag).length > 0);
      this.emit()
    })
  }
  $change_list_selected_item(payload) {
    this.$state.form.values.maxInteractTrace = payload.item.value;

    this.emit();
  }
}
export default class AgentSettingForm extends View {
  constructor(props){
    super(props);
    this.edit = this.edit.bind(this)
    this.cancel = this.cancel.bind(this)
    this.save = this.save.bind(this)
  }
  edit(){
    this.state.form.editable = true
    this.state.form.errors = {}
    this.setState({
      form:this.state.form
    })
  }
  cancel(){
    this.state.form.editable = false
    this.state.form.errors = {}
    this.setState({
      form:this.state.form
    })
  }
  listChangeingHandler(item) {
     dispatcher.dispatch({
       $type:'change_list_selected_item',
       item
     })
  }
  save(){
    saveAgentSettingApi({
      packageList: this.state.tags.join(','),
      activitySwitch:$(this.refs.activitySwitch).prop('checked'),
      gather:$(this.refs.gather).prop('checked'),
      httperrSwitch:$(this.refs.httperrSwitch).prop('checked'),
      httpSwitch:$(this.refs.httpSwitch).prop('checked'),
      httpHeaderSwitch:$(this.refs.httpHeaderSwitch).prop('checked'),
      frameRateSwitch:$(this.refs.frameRateSwitch).prop('checked'),
      webviewSwitch:$(this.refs.webviewSwitch).prop('checked'),
      maxInteractTrace:this.state.form.values.maxInteractTrace+''
    }).post().then((res) => {
      if(res.result){
        this.state.form.editable = false
        Success('保存成功')
      }else{
        Warning('保存失败')
      }
      this.forceUpdate()
    },(err) => {
      this.state.form.errors = err.errors
      this.forceUpdate()
    },() => {
      this.state.form.saving = true
      this.state.form.errors = {}
      this.forceUpdate()
    }).always(() => {
      this.state.form.saving = false
      this.forceUpdate()
    })
  }

  handleTagsChange(tags){
    this.setState({tags});
  }

  renderTag(index, tag, onRemove) {
    return (
      <span className="react-tagsinput-tag" key={index}>
        { tag }
        {
          this.state.packageName === tag ? null : <a className="react-tagsinput-remove" onClick={(e) => onRemove(index)} />
        }
      </span>
    )
  }

  render(){
    return this.state.form.values?(
      <div className="card">
        <h5 className="card-title">
          <div className="float-right">
          {
            this.state.form.saving?(
              <span>保存中 . . . </span>
            ):(
              this.state.form.editable?(
                [
                <button key="save" className="btn-green btn-xs" type="button" onClick={this.save}>
                  保存
                </button>,
                <button key="cancle" className="btn-gray btn-xs" type="button" onClick={this.cancel}>
                  取消
                </button>
                ]
              ):(
                <button className="btn-blue btn-xs" type="button" onClick={this.edit}>
                  修改
                </button>
              )
            )
          }
          </div>
          参数设置
          <sub style={{fontSize:12,marginLeft:15}}>
            { BlueWare.isAndroid ? '(Android Agent版本更新至2.0.2以上可用)' : '(iOS Agent版本更新至2.0.2以上可用)'}
          </sub>
        </h5>
        <div className="form-group horizontal">
          <div className="pure-g">
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="activitySwitch"
                       name="activitySwitch"
                       defaultChecked={this.state.form.values.activitySwitch}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集交互详情数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>关闭采集交互 Trace 数据，将无法定位造成慢交互的原因</p>
                ):null
              }
            </div>
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="gather"
                       name="gather"
                       defaultChecked={this.state.form.values.gather}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集崩溃详情数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>关闭采集崩溃 Trace 数据，将无法定位造成崩溃的原因</p>
                ):null
              }
            </div>
          </div>
          <div className="pure-g">
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="httperrSwitch"
                       name="httperrSwitch"
                       defaultChecked={this.state.form.values.httperrSwitch}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集网络错误详情数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>关闭采集网络错误 Trace 数据，将无法定位造成网络错误的原因</p>
                ):null
              }
            </div>
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="httpSwitch"
                       name="httpSwitch"
                       defaultChecked={this.state.form.values.httpSwitch}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集网络请求详情数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>关闭采集网络请求 Trace 数据，将无法定位造成慢请求的原因</p>
                ):null
              }
            </div>
          </div>
          <div className="pure-g">
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="httpHeaderSwitch"
                       name="httpHeaderSwitch"
                       defaultChecked={this.state.form.values.httpHeaderSwitch}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集 HTTP Request/Response Header 数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>打开采集 HTTP Request/Response Header 数据，有可能会暴露一些放在 header 里的敏感信息</p>
                ):null
              }
            </div>
            <div className="pure-u-1-2">
              <label>
                <input type="checkbox"
                       ref="webviewSwitch"
                       name="webviewSwitch"
                       defaultChecked={this.state.form.values.webviewSwitch}
                       disabled={!this.state.form.editable}
                />
                <span>是否采集 Web View 数据</span>
              </label>
              {
                this.state.form.editable?(
                  <p className="note" style={{paddingLeft:22}}>关闭采集 Web View 数据，将无法获取 Web View 加载信息。</p>
                ):null
              }
            </div>
          </div>
          {
            BlueWare.isAndroid ? (
              <div className="pure-g">
                <div className="pure-u-1-2">
                  <label>
                    <input type="checkbox"
                           ref="frameRateSwitch"
                           name="frameRateSwitch"
                           defaultChecked={this.state.form.values.frameRateSwitch}
                           disabled={!this.state.form.editable}
                    />
                    <span>是否采集卡顿数据</span>
                  </label>
                  {
                    this.state.form.editable?(
                      <p className="note" style={{paddingLeft:22}}>关闭采集卡顿数据，将无法定位造成 APP 不流畅的原因</p>
                    ):null
                  }
                </div>
              </div>
            ) : null
          }
          <div className="pure-g">
            <div className="pure-u-1-2">
              <ul className="form-group" style={{padding:0}}>
                <li>
                  <label className="control-label">交互详情记录采集阈值</label>
                  <DropdownList
                    style={{minWidth:'80px'}}
                    dropdownStyle={{minWidth:'80px'}}
                    current={_.find(this.state.list, item => item.value === this.state.form.values.maxInteractTrace.toString())}
                    list={this.state.list}
                    onChanging={this.listChangeingHandler.bind(this)}
                    disabled={!this.state.form.editable} />
                  {
                    this.state.form.editable?(
                      <p className="note" style={{clear:'both'}}>
                        以 Trace 采集阈值定义慢交互，阈值增大，则减少采集量；阈值减小，则会增大采集密度
                      </p>
                    ):null
                  }
                </li>
              </ul>
            </div>
          </div>
          {
            BlueWare.platform === 'Android' ? (
              <div className="pure-g">
                <div className={ classnames('pure-u-1-2', 'tags-input-box', {
                  disabled: ! this.state.form.editable
                }) }>
                  <label className="control-label">包名列表</label>
                  {
                    this.state.form.editable ? (
                        <TagsInput value={ this.state.tags } renderTag={ this.renderTag.bind(this) } ref="tagInput" addOnBlur={true} onlyUnique={ true } onChange={ this.handleTagsChange.bind(this) } />
                      ) : (
                        <div className="react-tagsinput">
                          {
                            this.state.tags.map((tag, index) => {
                              return (
                                <span className="react-tagsinput-tag" key={ index }>
                                  { tag }
                                  <a className="react-tagsinput-remove"></a>
                                </span>
                              )
                            })
                          }
                        </div>
                      )
                  }
                </div>
              </div>
            ) : null
          }
        </div>
      </div>
    ):null
  }
}
AgentSettingForm.defaultProps = {
  Scope:AgentSettingScope
}
